package com.exercise.rpc.common.registry.impl;/**
 * Created by kete on 2018-10-26.
 */

import com.exercise.rpc.common.registry.Constants;
import com.exercise.rpc.common.registry.ServiceDiscovery;
import com.exercise.rpc.common.registry.ServiceRegistry;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 作者：kete
 * 创建时间：2018-10-26 16:49
 * 功能描述：
 * 版本：
 */
public class ZookeeperRegistry implements ServiceRegistry {

    private static final Logger logger = LoggerFactory.getLogger(ZookeeperRegistry.class);

    private CountDownLatch latch = new CountDownLatch(1);

    private String registryAddress;


    public ZookeeperRegistry(String registryAddress) {

        this.registryAddress = registryAddress;
    }

    private ZooKeeper connectServer(){
        ZooKeeper zooKeeper = null;
        try {
            zooKeeper = new ZooKeeper(registryAddress, Constants.ZK_SESSION_TIMEOUT, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                }
            });

            latch.await();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return zooKeeper;

    }

    @Override
    public void register(String data) {
        if(!StringUtils.isEmpty(data)){
            ZooKeeper zooKeeper = connectServer();
            if(null != zooKeeper){
                addRootNode(zooKeeper);
                createNode(zooKeeper,data);
            }
        }

    }

    public void addRootNode(ZooKeeper zk){
        try {
            Stat s = zk.exists(Constants.ZK_REGISTRY_PATH, false);
            if (s == null) {
                zk.create(Constants.ZK_REGISTRY_PATH, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (KeeperException e) {
            logger.error(e.toString());
        } catch (InterruptedException e) {
            logger.error(e.toString());
        }
    }

    public void createNode(ZooKeeper zk,String data){
        try {
            byte[] bytes = data.getBytes();
            String path = zk.create(Constants.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            logger.debug("create zookeeper node ({} => {})", path, data);
        } catch (KeeperException e) {
            logger.error("", e);
        }
        catch (InterruptedException ex){
            logger.error("", ex);
        }
    }

    public static void main(String[] args) {
        ServiceRegistry registry = new ZookeeperRegistry("127.0.0.1:2181");

        registry.register("127.0.0.1:8080");

        registry.register("127.0.0.1:8081");

        ServiceDiscovery discovery = new ZookeeperDiscovery("127.0.0.1:2181");

        System.out.println("discovery = " + discovery.discover());
    }
}
